package pri.damai.xiaowu.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import pri.damai.xiaowu.auth.enums.ResultEnum;
import pri.damai.xiaowu.common.core.exception.GlobalException;

import java.io.IOException;
import java.time.Duration;

/**
 * Http 调用
 * @Desc
 * @Author DaMai
 * @Date 2021/8/5 18:15
 * 但行好事，莫问前程。
 */
@Configuration
@Slf4j
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {

        RestTemplate restTemplate = new RestTemplateBuilder()
                .requestFactory(OkHttp3ClientHttpRequestFactory::new)
                .setConnectTimeout(Duration.ofSeconds(15))
                .setReadTimeout(Duration.ofSeconds(15))
                .build();
        restTemplate.setErrorHandler(new MyRestErrorHandler());
        return restTemplate;
    }

    public static class MyRestErrorHandler implements ResponseErrorHandler {

        /**
         * 判断返回结果response是否是异常结果
         * 主要是去检查response 的HTTP Status
         * 仿造DefaultResponseErrorHandler实现即可
         */
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            int rawStatusCode = response.getRawStatusCode();
            HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
            return (statusCode != null ? statusCode.isError() : hasError(rawStatusCode));
        }

        protected boolean hasError(int unknownStatusCode) {
            HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
            return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
        }

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            log.error("HTTP 请求错误。状态码:{}, 响应体:{}", response.getStatusCode(), response);
            throw new GlobalException(ResultEnum.REQ_ERROR);
        }
    }

}
